<?php

abstract class Recommendation {
	
	protected $method_recommendation;
	
	protected function __construct(){
		
	}
	
	
	
	public static function initialize($type){
		switch($type){
			case RECOMMANDATION_ALEATOIRE:
				return new Recommendation_Random();
				break;
			case RECOMMANDATION_POPULAIRE:
				return new Recommendation_Popular();
				break;
				
			case RECOMMANDATION_POPULAIRE_AMIS:
				return new Recommendation_Popular_Friends();
				break;
			default:
				throw new Exception("Méthode de recommandation inconnue");
				break;
		}
		
	}
	
	public static function initalizeRandom(){
		
		if ($handle = opendir(REP_MOD_RECOMMANDATION_FILE)) {
			$recommendationFiles = array();
	    	while (false !== ($file = readdir($handle))) {
        		if ($file != "." && $file != ".." && preg_match('/^Recommendation_.*\.php$/',$file)) {
            		$recommendationFiles[]="$file";
        		}
    		}
    		closedir($handle);
			
		
			if (sizeof($recommendationFiles) > 0){
				$recommendationtype = preg_replace('/\.php/','',$recommendationFiles[mt_rand(0,sizeof($recommendationFiles)-1)]);
				$isInstanciable = call_user_func(array($recommendationtype,'canBeInstanciate')); // PHP 5.3 : $className::run();
				if ($isInstanciable)
					return new $recommendationtype();
				else
					return self::initalizeRandom();

			} else {
				throw new Exception("Erreur type Recommendation");
			}
		} else {
			throw new Exception("Erreur ouverture dossier modèle/Recommendation");
		}
				
	}
	
	public function next(){
		$query = $this->makeQuery();
		$title = $this->getTitleFromRecommendation($query);
		return $title;	
	}
	
	protected abstract function makeQuery();
	
	public static function canBeInstanciate() {
		throw new Exception('This method has to be overrided : canBeInstanciate()');
	}
	
	private function getTitleFromRecommendation($query){
		return Title_Bd::getTitleFromRecommendation($query);
	}
	
	
}

?>